<template>
  <div class="">
    <!--部门数据-->
    <!-- <el-col :span="4" :xs="24">
            <div class="head-container">
               <el-input
                  v-model="deptName"
                  placeholder="请输入部门名称"
                  clearable
                  prefix-icon="Search"
                  style="margin-bottom: 20px"
               />
            </div>
            <div class="head-container">
               <el-tree
                  :data="deptOptions"
                  :props="{ label: 'label', children: 'children' }"
                  :expand-on-click-node="false"
                  :filter-node-method="filterNode"
                  ref="deptTreeRef"
                  node-key="id"
                  highlight-current
                  default-expand-all
                  @node-click="handleNodeClick"
               />
            </div>
         </el-col> -->
    <!--用户数据-->
    <div class="pad10 box-shadow mgb10" v-show="showSearch">
      <el-form
        :model="queryParams"
        ref="queryRef"
        :inline="true"
        label-width="68px"
        class="fnmb"
      >
        <div class="flex jbetween">
          <div>
            <el-form-item label="登录账户" prop="Account">
              <el-input
                v-model="queryParams.Account"
                placeholder="请输入登录账户"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="用户名称" prop="Name">
              <el-input
                v-model="queryParams.Name"
                placeholder="请输入用户名称"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="手机号码" prop="Phone">
              <el-input
                v-model="queryParams.Phone"
                placeholder="请输入手机号码"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="用户类型" prop="Phone" v-if="!props.Type">
              <el-select
                v-model="queryParams.Type"
                clearable
                placeholder="请选择"
              >
                <el-option label="学生" :value="1" />
                <el-option label="职员" :value="2" />
                <el-option label="管理员" :value="3" />
              </el-select>
            </el-form-item>
            <el-form-item label="班级">
              <Selector
                v-model="queryParams.Class"
                category="班级级联"
                cascader="级联"
              ></Selector>
            </el-form-item>
          </div>
          <div class="flex acenter fnw jend">
            <el-button type="primary" icon="Search" round @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery" round>重置</el-button>
          </div>
        </div>
      </el-form>
    </div>
    <MyTable
      :tableList="userList"
      :total="Total"
      :columns="columns"
      v-model:page="page"
      v-model:searchStatus="showSearch"
      :btnList="$checkBtn(props.btnList['tab'])"
      @getList="getList"
      @edit="handleEdit"
      @delete="handleDelete"
      @radio="handleRadio"
      v-model:selectList="selectList"
      @custom="handleUpdatePassword"
      :activeRadio="props.activeRadio"
      :customBtn="
        $checkPermi(props.btnList['password']) ? [{ name: '改密码' }] : ''
      "
    >
      <template v-slot:tabTop>
        <el-row :gutter="10" v-if="props.showAdd">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="CirclePlusFilled"
              v-hasPermi="props.btnList['add']"
              round
              @click="handleAdd"
              >添加</el-button
            >
          </el-col>
        </el-row>
      </template>
    </MyTable>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="700px"
      append-to-body
      destroy-on-close
      draggable
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="userRef"
        label-width="100px"
        class="wid100"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名称" prop="Name">
              <el-input
                v-model="form.Name"
                placeholder="请输入用户名称"
                maxlength="30"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="Phone">
              <el-input
                v-model="form.Phone"
                placeholder="请输入手机号码"
                maxlength="11"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="登录账户" prop="Account">
              <el-input
                v-model="form.Account"
                placeholder="请输入登录账户"
                maxlength="30"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="title.includes('添加')">
            <el-form-item label="登录密码" prop="PWD">
              <el-input
                v-model="form.PWD"
                placeholder="请输入登录密码"
                type="password"
                maxlength="20"
                show-password
              />
            </el-form-item>
          </el-col>

          <el-col :span="12" v-if="!props.Type">
            <el-form-item label="用户类型" prop="Type">
              <el-select v-model="form.Type" clearable placeholder="请选择">
                <el-option label="学生" :value="1" />
                <el-option label="职员" :value="2" />
                <el-option label="管理员" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属班级" prop="ID_Class">
              <Selector
                category="班级级联"
                cascader="级联"
                v-model="form.ID_Class"
                v-model:placeholder="form.Name_Class"
              ></Selector>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="form.Type == 2 || form.Type == 3">
            <el-form-item label="所属部门" prop="ID_Dept">
              <Selector
                category="部门级联"
                cascader="级联"
                :checkStrictly="true"
                v-model="form.ID_Dept"
                v-model:placeholder="form.Name_Dept"
              ></Selector>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色">
              <Selector
                category="角色"
                v-model="form.RoleIDs"
                type="array"
              ></Selector>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否启用" prop="Enable">
              <el-radio-group v-model="form.Enable">
                <el-radio label="Y">启用</el-radio>
                <el-radio label="N">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 修改密码 -->
    <MyDialog
      :title="title"
      v-model:show="showUpdatePassword"
      width="500px"
      :formRef="formRef"
      @confirm="submitUpdatePassword"
    >
      <el-form :model="form" :rules="rules" ref="formRef">
        <el-form-item label="新密码" prop="PassWord">
          <el-input
            v-model="form.PassWord"
            type="password"
            show-password
            placeholder="请输入大小写英文、数字、符号不低于6个字符"
          ></el-input>
        </el-form-item>
      </el-form>
    </MyDialog>

    <el-drawer
      v-model="drawer"
      :title="title"
      direction="rtl"
      :size="566"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <template #default>
        <div class="flex acenter jcenter">
          <AddUserCom :FormData="form" ref="AddUserComRef"></AddUserCom>
        </div>
      </template>
      <template #footer>
        <div class="flex jcenter acenter">
          <el-button
            style="width: 40%; height: 45px; border-radius: 23px"
            type="primary"
            @click="submitForm"
            >保存</el-button
          >
          <el-button
            style="width: 40%; height: 45px; border-radius: 23px"
            type=""
            plain
            @click="drawer = false"
            >取消</el-button
          >
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup name="User">
import AddUserCom from '@/views/system/User/addUser';
import {
  listUser,
  EditUser,
  DelUser,
  AddUser,
  GetUserDetail,
  EditUserPWD
} from '@/api/system/user';
import { computed, onMounted, ref } from 'vue';
import { UserBindRole } from '@/api/system/role';
import useUserStore from '@/store/modules/user.js';
const emit = defineEmits(['update:checkList', 'radio']);
const router = useRouter();
const props = defineProps({
  checkbox: {
    default: false
  },
  checkList: {
    default: []
  },
  Type: {
    default: ''
  },
  userColumns: {
    default: []
  },
  btnList: {
    default: {
      tab: ['User:edit', 'User:delete'],
      add: ['User:add'],
      password: ['User:password']
    }
  },
  query: {
    default: {}
  },
  showAdd: { default: true },
  activeRadio: {
    default: ''
  },
  userManage: {
    default: true
  }
});
const { proxy } = getCurrentInstance();

const page = ref({
  PageIndex: 1,
  PageSize: 10
});
const formRef = ref({});
const userList = ref([]);
const open = ref(false);
const showSearch = ref(true);
if (!props.showAdd) {
  showSearch.value = false;
}
const Total = ref(0);
const title = ref('');
const dateRange = ref([]);
const deptName = ref('');
const showUpdatePassword = ref(false);
const drawer = ref(false);
const userRef = ref({});
const columns = ref([
  { label: '序号', visible: true },
  { label: '登录账户', visible: true, prop: 'Account' },
  { label: '用户名称', visible: true, prop: 'Name' },
  {
    label: '状态',
    visible: true,
    tag: true,
    prop: 'tags'
  },
  {
    label: '绑定',
    visible: true,
    tag: true,
    prop: 'bingTags'
  },
  { label: '电话号码', visible: true, prop: 'Phone' },
  { label: '用户类型', visible: true, prop: 'type' },
  { label: '创建时间', visible: true, prop: 'CreateTime' },
  { label: '创建人', visible: true, prop: 'CreateUser', user: true },
  { label: '修改时间', visible: true, prop: 'UpdateTime' },
  { label: '修改人', visible: true, prop: 'UpdateUser', user: true },
  { label: '操作', visible: true, width: 190 }
]);
if (props.Type) {
  columns.value = columns.value?.filter(item => item.label != '用户类型');
}
if (props.userColumns?.length) {
  columns.value = props.userColumns;
  proxy.$formatKey(columns.value);
}
const data = reactive({
  form: {
    Enable: 'Y',
    Sex: '男',
    SchoolState: 1,
    Type: props.Type,
    userManage: props.Type ? false : true
    // RoleIDs: [],
  },
  queryParams: {
    Account: '', //模糊搜素
    Name: '', //模糊搜素
    Phone: '', //模糊搜素
    Type: props.Type //类型 1:学生 2:职员 3:管理员
  },
  rules: {
    PassWord: [
      {
        required: true,
        pattern: /(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[\W_]).{6,}/,
        message: '大小写英文、数字、符号。并且长度不可低于6位数',
        trigger: 'blur'
      }
    ],
    Name: [
      { required: true, message: '用户名称不能为空', trigger: 'blur' },
      {
        min: 2,
        max: 20,
        message: '用户名称长度必须介于 2 和 20 之间',
        trigger: 'blur'
      }
    ],
    Account: [{ required: true, message: '登录账户不能为空', trigger: 'blur' }],
    PWD: [
      { required: true, message: '登录密码不能为空', trigger: 'blur' },
      {
        min: 6,
        max: 20,
        message: '用户密码长度必须介于 6 和 20 之间',
        trigger: 'blur'
      }
    ],
    Enable: [
      {
        required: true,
        message: '请选择用户类型',
        trigger: 'change'
      }
    ],
    Phone: [
      {
        required: true,
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: '请输入正确的手机号码',
        trigger: 'blur'
      }
    ],
    Type: [
      {
        required: true,
        message: '请选择用户类型',
        trigger: 'change'
      }
    ],
    // RoleIDs: [
    //   {
    //     required: true,
    //     message: '请选择角色',
    //     trigger: 'change'
    //   }
    // ],
    ID_Class: [
      {
        required: true,
        message: '请选择班级',
        trigger: 'change'
      }
    ],
    ID_Dept: [
      {
        required: true,
        message: '请选择部门',
        trigger: 'change'
      }
    ]
  }
});

const selectList = computed({
  get: () => {
    return props.checkList;
  },
  set: v => {
    console.log(v);
    emit('update:checkList', v);
  }
});
const { queryParams, form, rules } = toRefs(data);

onMounted(() => {
  getList();
});

function handleRadio(row) {
  emit('radio', row);
}

async function submitUpdatePassword(val) {
  console.log(val);
  if (val) {
    try {
      let query = {
        ...form.value
      };
      await EditUserPWD(query);
      proxy.$modal.msgSuccess('修改成功');
      showUpdatePassword.value = false;
    } catch (error) {
      console.log(error);
    }
  }
}

function handleUpdatePassword(row) {
  title.value = '修改密码';
  form.value.ID = row.ID;
  form.value.PassWord = '';
  showUpdatePassword.value = true;
}

/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};
/** 根据名称筛选部门树 */
watch(deptName, val => {
  proxy.$refs['deptTreeRef'].filter(val);
});

function filterUserType(type) {
  switch (type) {
    case 1:
      return '学生';
    case 2:
      return '职员';
    case 3:
      return '管理员';
  }
}

/** 查询用户列表 */
async function getList() {
  try {
    let query = {
      ...page.value,
      ...queryParams.value,
      ...props.query
    };
    let res = await listUser(query);
    res.data.List?.forEach(item => {
      item.type = filterUserType(item.Type);
      item.tags = [
        {
          name: item.Enable == 'Y' ? '启用' : '停用',
          type: item.Enable == 'Y' ? 'success' : 'danger'
        }
      ];
      item.bingTags = [
        {
          name: item.WxOpenID ? '已绑定' : '未绑定',
          type: item.WxOpenID ? 'success' : 'danger'
        }
      ];
    });

    userList.value = res.data.List;
    Total.value = res.data.Total;
  } catch (error) {
    console.log(error);
  }
  //   loading.value = true;
  //   listUser(proxy.addDateRange(queryParams.value, dateRange.value)).then(
  //     (res) => {
  //       loading.value = false;
  //       userList.value = res.rows;
  //       total.value = res.total;
  //     }
  //   );
}
/** 节点单击事件 */
function handleNodeClick(data) {
  queryParams.value.deptId = data.id;
  handleQuery();
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm('queryRef');
  queryParams.value.deptId = undefined;
  // proxy.$refs.tree.setCurrentKey(null);
  handleQuery();
}
/** 删除按钮操作 */
async function handleDelete(row) {
  try {
    await DelUser({ ID: row.ID });
    proxy.$modal.msgSuccess('删除成功');
    getList();
  } catch (error) {
    console.log(error);
  }
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    'system/user/export',
    {
      ...queryParams.value
    },
    `user_${new Date().getTime()}.xlsx`
  );
}
/** 用户状态修改  */
function handleStatusChange(row) {
  let text = row.status === '0' ? '启用' : '停用';
  proxy.$modal
    .confirm('确认要"' + text + '""' + row.Name + '"用户吗?')
    .then(function () {
      return changeUserStatus(row.userId, row.status);
    })
    .then(() => {
      proxy.$modal.msgSuccess(text + '成功');
    })
    .catch(function () {
      row.status = row.status === '0' ? '1' : '0';
    });
}

/** 重置操作表单 */
function reset() {
  form.value = {
    Name: undefined,
    Account: undefined,
    PWD: undefined,
    Phone: undefined,
    Enable: 'Y',
    Sex: '男',
    SchoolState: 1,
    userManage: props.Type ? false : true,
    RoleIDs: [],
    Type: props.Type,
    ID_Class: '',
    ID_Dept: ''
  };
  // setTimeout(() => {
  proxy.resetForm('userRef');
  // });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 新增按钮操作 */
function handleAdd() {
  // reset();
  // open.value = true;
  switch (Number(props.Type)) {
    case 1:
      title.value = '添加学员';
      break;
    case 2:
      title.value = '添加职员';
      break;
    default:
      title.value = '添加用户';
  }

  nextTick(() => {
    reset();
    proxy.$refs['AddUserComRef'].userRef.resetFields();
  });
  drawer.value = true;
}
/** 修改按钮操作 */
async function handleEdit(row) {
  reset();
  try {
    let { data } = await GetUserDetail({ ID: row.ID });

    form.value = {
      ...data.Info,
      Type: props.Type ? props.Type : data.Info.Type, //类型 1:学生 2:职员 3:管理员,
      Ancestral: data.Info.Ancestral?.split('/'),
      userManage: props.Type ? false : true
    };

    form.value.RoleIDs = data.Roles?.map(item => item.ID_Role);
    switch (Number(form.value.Type)) {
      case 1:
        title.value = '修改学员';
        break;
      case 2:
        title.value = '修改职员';
        break;
      default:
        title.value = '修改用户';
    }

    drawer.value = true;
  } catch (error) {
    console.log(error);
  }
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs['AddUserComRef'].userRef.validate(async valid => {
    let query = {
      ...form.value,
      Ancestral:
        typeof form.value.Ancestral == 'object'
          ? form.value.Ancestral?.join('/')
          : form.value.Ancestral
    };

    if (!query.Avatar) {
      return proxy.$modal.msgError('头像不能为空');
    }
    if (!query.Name) {
      return proxy.$modal.msgError('个人资料-姓名 不能为空');
    }
    if (!query.Phone) {
      return proxy.$modal.msgError('个人资料-手机号码 不能为空');
    }
    if (
      (!query.ID_Dept && query.Type == 2) ||
      (!query.ID_Dept && query.Type == 3)
    ) {
      return proxy.$modal.msgError('在校资料-所属部门 不能为空');
    }
    if (!query.ID_Class && query.Type == 1) {
      return proxy.$modal.msgError('在校资料-所属班级 不能为空');
    }
    if (!query.Account) {
      return proxy.$modal.msgError('系统资料-登录账号 不能为空');
    }
    if (!query.RoleIDs.length) {
      return proxy.$modal.msgError('系统资料-账号角色 不能为空');
    }
    if (valid) {
      try {
        if (form.value.ID != undefined) {
          await EditUser(query);
          await UserBindRole({
            RoleIDs: form.value.RoleIDs,
            UserID: form.value.ID
          });
          if (form.value.ID == useUserStore().userInfo?.ID) {
            useUserStore().editStoreUser(query);
          }
          proxy.$modal.msgSuccess('修改成功');
          open.value = false;
          drawer.value = false;
          getList();
        } else {
          let res = await AddUser(query);
          if (form.value.RoleIDs?.length) {
            await UserBindRole({
              RoleIDs: form.value.RoleIDs,
              UserID: res.data
            });
          }
          proxy.$modal.msgSuccess('新增成功');
          open.value = false;
          drawer.value = false;
          getList();
        }
      } catch (error) {
        console.log(error);
      }
    }
  });
}
</script>
<style lang="scss">
.el-drawer__header {
  padding-top: 10px;
  margin-bottom: 0;
}
</style>
